import { Button, DatePicker, Input, NavBar, Modal } from 'antd-mobile'
import Icon from '@/components/icon'
import './index.scss'
import classNames from 'classnames'
import { billListData } from '@/containts'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { useState} from 'react'
import { useDispatch } from 'react-redux'
import { addBillList, updateBillList } from '@/store/modules/billStore'
import dayjs from 'dayjs'
import { setCurrentMonth } from '@/store/modules/billStore'
import useBillItem from '@/hooks/useBillItem'

const New = () => {
  const navigate = useNavigate()
  const [params] = useSearchParams()
  const id = params.get('id')
  const [BillItem] = useBillItem(id)

  //收入：income，支出：pay
  const [billType, setBillType] = useState(id ? BillItem.type : 'income')

  //输入的金额 = inputRef.current.value 获取不到ant design组件的输入值
  //原生dom可以。
  //const inputRef = useRef(null)

  //输入的金额
  const [money, setMoney] = useState(id ? BillItem.money : 0)

  // 收集账单类型
  const [useFor, setUseFor] = useState(id ? BillItem.useFor : '')

  //选择的时间
  const [time, setTime] = useState(id ? BillItem.date : new Date())

  //时间选择器的显示与关闭
  const [dateVisible, setDateVisible] = useState(false)

  const dispatch = useDispatch()
  //保存账单事件

  function sabeBill() {
    if (money === 0 || money === "" || useFor === "") {
      Modal.alert({
        content: '输入错误！请检查！',
      })
      return
    }
    const data = {
      type: billType,
      money: billType === 'income' ? +money : -money,
      date: time,
      useFor: useFor
    }

    if (id) {
      const upData = {
        ...data,
        id: id
      }
      updData(upData)
    } else {
      sendData(data)
    }

  }
  const sendData = async (data) => {
    await dispatch(addBillList(data))
    await Modal.alert({
      content: '添加成功！请在账单页里确认添加的账单。',
    })
    dispatch(setCurrentMonth(dayjs(time).format('YYYY-MM')))
    navigate('/')
  }

  const updData = async (upData) => {
    await dispatch(updateBillList(upData))
    await Modal.alert({
      content: '更新成功！请在账单页里确认更新的账单。',
    })
    dispatch(setCurrentMonth(dayjs(time).format('YYYY-MM')))
    navigate('/')
  }

  return (
    <div className="keepAccounts">
      <NavBar className="nav" onBack={() => navigate(-1)}>
        {id ? '更新账单' : '记一笔'}
      </NavBar>

      <div className="header">
        <div className="kaType">
          <Button
            shape="rounded"
            className={classNames({ 'selected': billType === 'pay' })}
            onClick={() => setBillType('pay')}
          >
            支出
          </Button>
          <Button
            className={classNames({ 'selected': billType === 'income' })}
            shape="rounded"
            onClick={() => setBillType('income')}
          >
            收入
          </Button>
        </div>

        <div className="kaFormWrapper">
          <div className="kaForm">
            <div className="date" onClick={() => setDateVisible(true)}>
              <Icon type="calendar" className="icon" />
              <span className="text">{dayjs(time).format('YYYY-MM-DD')}</span>
              <DatePicker
                className="kaDate"
                title="记账日期"
                max={new Date()}
                visible={dateVisible}

                onConfirm={(time) => {
                  setTime(time)
                  setDateVisible(false)
                }}

                onClose={() => setDateVisible(false)}
              />
            </div>
            <div className="kaInput">
              <Input
                className="input"
                placeholder="0.00"
                type="number"
                value={money}
                onChange={(value) => setMoney(value)}
              />
              <span className="iconYuan">¥</span>
            </div>
          </div>
        </div>
      </div>

      <div className="kaTypeList">
        {billListData[billType].map(item => {
          return (
            <div className="kaType" key={item.type}>
              <div className="title">{item.name}</div>
              <div className="list">
                {item.list.map(item => {
                  return (
                    <div
                      className={classNames(
                        'item',
                        { 'selected': item.type === useFor }
                      )}
                      key={item.type}
                      onClick={() => setUseFor(item.type)}
                    >
                      <div className="icon">
                        <Icon type={item.type} />
                      </div>
                      <div className="text">{item.name}</div>
                    </div>
                  )
                })}
              </div>
            </div>
          )
        })}
      </div>

      <div className="btns">
        <Button className="btn save" onClick={sabeBill}>
          {id ? '更 新' : '保 存'}
        </Button>
      </div>
    </div>
  )
}

export default New